package com.itheima.store.web.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.store.domain.User;
import com.itheima.store.service.UserService;
import com.itheima.store.service.impl.UserServiceImpl;
import com.itheima.store.utils.BaseServlet;
import com.itheima.store.utils.BeanFactory;

import com.itheima.store.utils.MyDateConverter;

import dingtalk.org.access.util.ServiceResult;
import dingtalk.org.access.vo.EmpSimpileVO;



/**
 * 用户模块的Servlet:
 */
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	 
	    
	    
	/**
	 * 跳转到注册页面的执行的方法：registUI
	 */
	public String registUI(HttpServletRequest req,HttpServletResponse resp){
		return "/jsp/regist.jsp";
	}
	
	/**
	 * 异步校验用户名的执行的方法: checkUsername
	 */
	public String checkUsername(HttpServletRequest req,HttpServletResponse resp){
		try{
			// 接收参数:
			String username = req.getParameter("user_name");
			//DingServlet Ding= new DingServlet();
			// String serviceResult = Ding.getUserId(req, resp, "4b8a4754563b32d88060adcd206a3ec5");
		     //   System.err.println(JSON.toJSONString(serviceResult));
			// 调用业务层:
//			UserService userService = new UserServiceImpl();
			UserService userService = (UserService) BeanFactory.getBean("userService");
			List<User> existUser = userService.findByUsername(username);
			if(existUser == null ||existUser.size()==0){
				// 用户名可以使用:
				resp.getWriter().println("1");
			}else{
				// 用户名已经存在:
				if("1".equals(existUser.get(0).getIsforbidden())) {
					resp.getWriter().println("3");
				}else {
					resp.getWriter().println("2");
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		return null;
	}
	
	/**
	 * 用户注册的执行的方法:regist
	 */
	public String regist(HttpServletRequest req,HttpServletResponse resp){
		try{
			// 接收数据:
			Map<String,String[]> map = req.getParameterMap();
			// 封装数据:
			User user = new User();
			ConvertUtils.register(new MyDateConverter(), Date.class);
			BeanUtils.populate(user, map);
			req.setAttribute("user", user);
			// 一次性验证码程序:
			String code1 = req.getParameter("code");
			String code2 = (String)req.getSession().getAttribute("code");
			req.getSession().removeAttribute("code");
			if(!code1.equalsIgnoreCase(code2)){
				req.setAttribute("msg", "验证码输入错误!");
				
				return "/jsp/regist.jsp";
			}
			// 调用业务层:
			UserService userService = (UserService) BeanFactory.getBean("userService");
			userService.save(user);
			// 页面跳转:
			req.setAttribute("msg", "注册成功！请去邮箱激活!");
			return "/jsp/msg.jsp";
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
		
	}
	
	/**
	 * 用户激活的方法:
	 * @param req
	 * @param resp
	 * @return
	 */
	public String active(HttpServletRequest req,HttpServletResponse resp){
		// 接收激活码：
		String code = req.getParameter("code");
		// 根据激活码查询:
		UserService userService = (UserService) BeanFactory.getBean("userService");
		User existUser;
		try {
			existUser = userService.findByCode(code);
			// 判断
			if(existUser == null){
				// 激活码有误:
				req.setAttribute("msg", "激活码错误！请重新激活！");
			}else{
				// 激活操作:
			//	existUser.setState(2); // 设置激活的状态为已经激活.
				existUser.setCode(null);
				userService.update(existUser);
				req.setAttribute("msg", "激活成功！请去登录！");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "/jsp/msg.jsp";
	}
	
	/**
	 * 跳转到登录页面的执行的方法:loginUI
	 */
	public String loginUI(HttpServletRequest req,HttpServletResponse resp){
		User user = (User) req.getSession().getAttribute("existUser");
		if(user==null){
			return "/jsp/login.jsp";

		}else{
			return "/index.jsp";
		}
			}
	
	/**
	 * 用户登录的执行的方法:login
	 */
	public String login(HttpServletRequest req,HttpServletResponse resp){
		try{
			// 接收参数:
			Map<String,String[]> map = req.getParameterMap();
			// 封装数据：
			User user = new User();
			BeanUtils.populate(user, map);
			req.setAttribute("user", user);
			// 一次性验证码程序:
			String code1 = req.getParameter("code");
			String code2 = (String)req.getSession().getAttribute("code");
			req.getSession().removeAttribute("code");
			if(!code1.equalsIgnoreCase(code2)){
				req.setAttribute("msg", "验证码输入错误!");
				
				return "/jsp/login.jsp";
			}
			
		
			// 调用业务层:
			UserService userService = (UserService) BeanFactory.getBean("userService");
			
			User existUser = userService.login(user);
			if(existUser == null){
				req.setAttribute("msg", "用户名或密码错误!");
				return "/jsp/login.jsp";
			}else{
				//增加后台校验用户锁定情况登录行为，防止用户恶意登录
				if(existUser.getIsforbidden().equals("1")) {
					req.setAttribute("msg", "该用户已经被锁定，请联系管理员！");
					return "/jsp/login.jsp";
				}
				// 登录成功:自动登录
				String autoLogin = req.getParameter("autoLogin");
				if("true".equals(autoLogin)){
					Cookie cookie = new Cookie("autoLogin", existUser.getUser_name()+"#"+existUser.getUser_password());
					cookie.setPath("/store_v2.0");
					cookie.setMaxAge(7* 24 * 60 * 60);
					resp.addCookie(cookie);
				}
				
				// 记住用户名:
				String remember = req.getParameter("remember");
				if("true".equals(remember)){
					Cookie cookie = new Cookie("username",existUser.getUser_name());
					cookie.setPath("/store_v2.0");
					cookie.setMaxAge(24 * 60 * 60);
					resp.addCookie(cookie);
				}
				
				req.getSession().setAttribute("existUser", existUser);
				resp.sendRedirect(req.getContextPath()+"/index.jsp");
				return null;
			}
			// 页面跳转
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
	
	/**
	 * 跳转到修改密码界面
	 * @param req
	 * @param resp
	 * @return
	 */
public String alterPasswordUI(HttpServletRequest req,HttpServletResponse resp) {
		
		return "/jsp/alterPassword.jsp";
		
	}
	/**
	 * 修改密码
	 * @param req
	 * @param resp
	 * @return
	 */
	public String alterPassword(HttpServletRequest req,HttpServletResponse resp) {
		try {
			Map<String, String[]> map = req.getParameterMap();
			User user = new User();
			BeanUtils.populate(user, map);
			User existUser = (User)req.getSession().getAttribute("existUser");
			user.setUser_id(existUser.getUser_id());
			UserService userService = (UserService) BeanFactory.getBean("userService");
			User userUP = userService.findByUsernameAndPassword(existUser.getUser_name(),user.getUser_password());
			if(userUP != null) {
				userService.alertPassword(user);
				
				req.setAttribute("msg", "修改密码成功!");
				
				return "/jsp/success.jsp";
			}else {
				req.setAttribute("msg", "原密码有误!");
				return "/jsp/alterPassword.jsp";
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("修改密码时出错了！");
		}
		
		
	}
	
	
	
	
	/**
	 * 用户退出功能的方法:logOut
	 * @param req
	 * @param resp
	 * @return
	 */
	public String logOut(HttpServletRequest req,HttpServletResponse resp){
		
		try {
			// 销毁session
			req.getSession().invalidate();
			// 清空自动登录的Cookie:
			Cookie cookie = new Cookie("autoLogin","");
			cookie.setPath("/store_v2.0");
			cookie.setMaxAge(0);
			resp.addCookie(cookie);
			
			resp.sendRedirect(req.getContextPath()+"/index.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("null")
	public void loginDing(String name) {
		// 调用业务层:
					UserService userService = (UserService) BeanFactory.getBean("userService");
					User existUser =null;
					try {
						existUser =  userService.loginDing(name);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					 
					    HttpServletRequest request = null; //这里可以获取到request
						request.getSession().setAttribute("existUser", existUser);
						String ss= (String) request.getAttribute("existUser");
		
	}
	
	
	
	
	
}
